@echo off
REM FlinkCEP 快速启动脚本
REM 用于快速启动整个开发环境

echo ========================================
echo FlinkCEP 快速启动脚本
echo ========================================

REM 检查Docker是否安装
docker --version >nul 2>&1
if %ERRORLEVEL% neq 0 (
    echo 错误: Docker 未安装或未启动
    echo 请先安装并启动 Docker Desktop
    pause
    exit /b 1
)

REM 检查Docker Compose是否可用
docker compose version >nul 2>&1
if %ERRORLEVEL% neq 0 (
    echo 错误: Docker Compose 不可用
    echo 请确保 Docker Desktop 已正确安装
    pause
    exit /b 1
)

REM 设置项目目录
set PROJECT_DIR=%~dp0..
cd /d "%PROJECT_DIR%"

echo 当前目录: %CD%

REM 检查是否已编译项目
if not exist "target\flink-cep-1.0.0.jar" (
    echo 项目尚未编译，开始编译...
    call mvn clean package -DskipTests
    if %ERRORLEVEL% neq 0 (
        echo 编译失败，请检查错误信息
        pause
        exit /b 1
    )
    echo 编译完成
)

echo.
echo 1. 启动基础服务 (Kafka, Zookeeper, Mock Backend)...
cd docker
docker compose up -d zookeeper kafka kafka-ui mock-backend

REM 等待服务启动
echo 等待服务启动...
timeout /t 30 /nobreak >nul

REM 检查Kafka是否就绪
echo 检查Kafka服务状态...
docker compose exec kafka kafka-broker-api-versions --bootstrap-server localhost:9092 >nul 2>&1
if %ERRORLEVEL% neq 0 (
    echo 警告: Kafka 可能尚未完全启动，请稍后重试
)

REM 创建Kafka主题
echo 创建Kafka主题: input-events
docker compose exec kafka kafka-topics --create --topic input-events --bootstrap-server localhost:9092 --partitions 3 --replication-factor 1 2>nul
if %ERRORLEVEL% equ 0 (
    echo Kafka主题创建成功
) else (
    echo Kafka主题可能已存在或创建失败
)

echo.
echo 2. 启动Flink集群...
docker compose up -d flink-jobmanager flink-taskmanager

REM 等待Flink启动
echo 等待Flink集群启动...
timeout /t 20 /nobreak >nul

cd ..

echo.
echo ========================================
echo 环境启动完成！
echo ========================================
echo.
echo 服务访问地址:
echo - Kafka UI:        http://localhost:8080
echo - Flink Web UI:    http://localhost:8081
echo - Mock Backend:    http://localhost:1080
echo.
echo Kafka 配置:
echo - Bootstrap Server: localhost:9092
echo - Topic:           input-events
echo.
echo 下一步操作:
echo 1. 启动FlinkCEP应用: scripts\start-flink-cep.bat
echo 2. 生成测试数据:     python scripts\sample-data-generator.py
echo 3. 查看日志:         docker compose -f docker\docker-compose.yml logs -f
echo.
echo 停止所有服务: docker compose -f docker\docker-compose.yml down
echo ========================================

pause